<template>
  <SimpleControl :control="control" :show-custom-setting="true" hide-offline-tips-forced>
    <template #custom-setting>
      <view class="vocie-open" @click="openVoicePage">
        <view class="vocie-img">
          <image src="@/assets/coupon/Voice.png" mode="aspectFit"></image>
        </view>
        <view class="vocie-text">{{ $t('RefrigeratorB.RefrigeratorBswitch.Vocie.Text') }}</view>
      </view>
    </template>
    <view class="screen-view" v-if="isShowScreen && !control.store.isOffline">
      <view class="screen-value" v-for="items in [1, 2, 3]"></view>
    </view>
    <view :class="{ 'is-off-line': control.store.isOffline }" v-else>
      <RefrigeratorBswitch
        @change-component="changeComponent"
        :expired-num="expiredNum"
        :show-save-manger="isShowSaveManager"
      />
      <!-- 功能控制 -->
      <RefrigertorBsetting
        :control="control"
        v-show="isSwitchRibbon === 'RefrigeratorB.RefrigeratorBswitch.control.Text'"
        @open-setting="openSetting"
      />
      <!-- 储存管理 -->
      <RefrigertorBSaveManger
        v-show="isSwitchRibbon === 'RefrigeratorB.RefrigeratorBswitch.StorageManagement.Text'"
        :control="control"
        :tory-list="toryList"
        @refsh-data="getToryList"
        @show-add="showAddHandle"
      />
    </view>

    <RefrigeratorBSettingModal
      :control="control"
      :show="showSettingModal"
      @close="settingModalClose"
    ></RefrigeratorBSettingModal>
    <RefrigeratorBAdd
      style="height: 80vh"
      :show="isShowAdd"
      :control="control"
      @close="closeAddDrawer"
      :edit-items="editItems"
    ></RefrigeratorBAdd>
    <PageModal :show="isVoicePage" @close="closeVoicePage" :title="$t('RefrigeratorB.RefrigeratorBswitch.Vocie.Text')">
      <RefrigeratorVoice :show="isVoicePage"></RefrigeratorVoice>
    </PageModal>
  </SimpleControl>
</template>

<script setup lang="ts">
import type {
  RefrigeratorBController,
  RefrigeratorBSettingGroup,
  RefrigeratorBToryList,
  PayloadData,
} from '@/controller/RefrigeratorB/definition'
import SimpleControl from '@/pages/appliance/view/control/simpleControl.vue'
import RefrigeratorBswitch from './RefrigeratorBswitch.vue'
import RefrigertorBSaveManger from './RefrigertorBSaveManger.vue'
import RefrigertorBsetting from './RefrigertorBsetting.vue'
import RefrigeratorBSettingModal from './RefrigeratorSettingModal.vue'
import RefrigeratorVoice from './RefrigeratorVoice.vue'
import { showLoading } from '@/utils/mpHelper'
import { getInventoryList, getInventoryDetail } from '@/api/refrigetorB'
import RefrigeratorBAdd from './RefrigeratorBAdd.vue'
import PageModal from '@/common/pageModal.vue'
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { requestSubscribeUsingComplete } from '@/utils/mpHelper'
import netconfig from '@/config/netconfig'
import type { OTAHelper } from '../settings/ota/helpers/types'
import { useControlState } from '@/controller/BaseAppliance/useControl'
import { createOtaHelper } from '../settings/ota/helpers'

const props = defineProps<{
  control: RefrigeratorBController.Control
}>()
const isSwitchRibbon = ref('RefrigeratorB.RefrigeratorBswitch.control.Text')
const isShowScreen = ref(true)
const showSettingModal = ref(false)
const toryList = ref<RefrigeratorBToryList[] | []>([])
const isShowAdd = ref(false)
const freshStorageGroupKey = computed(() => props.control.store._datasource.settings)
const cosmeticsId = ref<string | number>(0)
const isShowSaveManager = ref(false)

const controlState = useControlState(props.control)
const { isOffline } = controlState
const { store } = props.control

let otaHelper: OTAHelper | null = null
watch(
  () => props.control.store.isOffline,
  (isOffline) => {
    if (!isOffline) {
      getToryList().then(() => {
        isShowScreen.value = false
      })
    }
  }
)
onLoad((options: any) => {
  if (options?.remind_type === 'cosmetics_add_remind') {
    if (options?.cosmetics_id) {
      cosmeticsId.value = options?.cosmetics_id
      isShowSaveManager.value = true
    }
  } else if (options?.remind_type === 'cosmetics_expire_remind') {
    isShowSaveManager.value = true
  }
  // 创建固件升级方法
  otaHelper = createOtaHelper({
    brand: options?.brand || '',
    type: options?.type || '',
    vib: options?.vib || '',
    haId: options?.haId || '',
    scene: 'detail',
  })
})
watch(
  () => cosmeticsId.value,
  () => {
    getEditems()
  }
)
/**
 * 初始详情
 */
async function getEditems() {
  const res = await getInventoryDetail(cosmeticsId.value as string)
  if (res.code === 0) {
    showAddHandle(res.data)
  }
}
/**
 * 编辑页
 * @param item
 */
const editItems = ref()
function showAddHandle(item?: PayloadData) {
  editItems.value = item
  isShowAdd.value = true
}
/**
 * 语音贴士
 */
const isVoicePage = ref(false)
function closeVoicePage() {
  isVoicePage.value = false
}
function openVoicePage() {
  isVoicePage.value = true
  safeTrack(() => {
    trackEvent('RefrigeratorB.RefrigeratorBswitch.vocie.text', {}, TrackType.ApplianceDetail)
  })
}
/**
 * 储存管理
 */
const expiredNum = ref(0)
function closeAddDrawer() {
  isShowAdd.value = false
  getToryList()
}
watch(
  () => props.control.store.$state.inventoryContent,
  () => {
    if (props.control.store.$state.inventoryContent) {
      getToryList()
    }
  }
)
/**
 * ota升级
 */
watchEffect(() => {
  if (isOffline.value === false && otaHelper) {
    otaHelper.checkUpgrade()
    store.updateDetected = otaHelper?.upgradeDetected.value as boolean
  }
})
async function getToryList() {
  await getInventoryList(props.control.store._datasource.haId).then((res) => {
    if (res.code === 0) {
      toryList.value = res.data?.payload as RefrigeratorBToryList[]
      expiredNum.value = res.data?.payload.length === 0 ? 0 : res.data?.payload[0].expireCount
    }
  })
}
async function changeComponent(key: string) {
  isSwitchRibbon.value = key
  if (key === 'RefrigeratorB.RefrigeratorBswitch.StorageManagement.Text') {
    await requestSubscribeUsingComplete([netconfig.DeviceStateId])
  }
}

async function openSetting(settingGroup: RefrigeratorBSettingGroup) {
  await showLoading(() => props.control.store.loadMenuSettings(settingGroup.key))
  showSettingModal.value = true
}
function settingModalClose() {
  showSettingModal.value = false
  getToryList()
}
</script>
<style lang="less" scoped>
.screen-view {
  .screen-value {
    width: 90%;
    height: 100rpx;
    margin: auto;
    background-color: #f4f4f6;
    margin-top: 30rpx;
  }
}
.is-off-line {
  pointer-events: none;
  opacity: 0.6;
}
.vocie-open {
  text-align: center;
  margin-right: 40rpx;
  .vocie-img {
    width: 40rpx;
    height: 40rpx;
    margin: auto;
    & > image {
      width: 100%;
      height: 100%;
    }
  }
  .vocie-text {
    display: block;
    margin-top: 4rpx;
    font-size: 20rpx;
    font-weight: 400;
    line-height: 24rpx;
  }
}
</style>
